<template>
  <el-form :model="editData" label-width="120px" class="edit-station-form">
    <!-- 图片上传 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="站点图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/upload/images"
              :file-list="fileList"
              list-type="picture-card"
              :limit="1"
              :auto-upload="true"
              :on-success="handleUploadSuccess"
              :on-remove="handleUploadRemove"
              :on-exceed="handleExceed"
          >
            <i v-if="fileList.length === 0" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 基本信息 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="站点名称">
          <el-input v-model="editData.stationName" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="站点代码">
          <el-input v-model="editData.stationCode" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="站点类型">
          <el-input v-model="editData.stationType" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="站点属性">
          <el-input v-model="editData.stationProperty" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="18">
        <el-form-item label="详细地址">
          <el-input v-model="editData.address" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="充电桩数量">
          <!-- 直接取数组 length 即可 -->
          <el-input-number :model-value="editData.chargingPiles.length" disabled />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 第二部分 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="开店时间">
          <el-time-picker
              v-model="editData.openTime"
              placeholder="请选择开门时间"
              value-format="HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="运营状态">
          <el-radio-group v-model="editData.status">
            <el-radio label="正常">正常</el-radio>
            <el-radio label="已下线">已下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="关店时间">
          <el-time-picker
              v-model="editData.closeTime"
              placeholder="请选择关门时间"
              value-format="HH:mm:ss"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="店面是否开启评价" label-width="175">
          <el-switch
              v-model="editData.enableEvaluation"
              active-text="是"
              inactive-text="否"
              width="45"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 电站简介 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="电站简介">
          <v-md-editor
              v-model="editData.stationIntro"
              height="400px"
              placeholder="请输入简介的 Markdown 内容"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 充电桩列表 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="充电桩列表">
          <el-table :data="editData.chargingPiles" style="width: 100%" border>
            <el-table-column prop="pileName" label="充电桩名称" />
            <el-table-column prop="pileCode" label="充电桩编号" />
            <el-table-column prop="pileType" label="类型" />
            <el-table-column prop="pilePower" label="功率(kW)" />
            <el-table-column prop="pileModel" label="型号" />
            <el-table-column prop="pileDesc" label="描述" />
            <el-table-column prop="suitableVehicle" label="适用车型" />
            <el-table-column label="操作">
              <template #default="{ row, $index }">
                <el-button size="small" @click="openEditPileDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="removePile($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="openNewPileDialog">新增充电桩</el-button>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 底部按钮 -->
    <div style="text-align: right; margin-top: 15px;">
      <el-button @click="cancelDialog">取消</el-button>
      <el-button type="primary" @click="saveForm">保存</el-button>
    </div>
  </el-form>

  <!-- 新增充电桩 弹窗 -->
  <el-dialog v-model="pileDialogVisible" title="新增充电桩">
    <el-form :model="newPileForm" label-width="120px">
      <el-form-item label="充电桩名称">
        <el-input v-model="newPileForm.pileName"></el-input>
      </el-form-item>

      <el-form-item label="充电桩编号">
        <!-- 新增时可编辑编号 -->
        <el-input v-model="newPileForm.pileCode"></el-input>
      </el-form-item>

      <el-form-item label="类型">
        <el-input v-model="newPileForm.pileType"></el-input>
      </el-form-item>

      <el-form-item label="功率(kW)">
        <el-input-number v-model="newPileForm.pilePower"></el-input-number>
      </el-form-item>

      <el-form-item label="型号">
        <el-input v-model="newPileForm.pileModel"></el-input>
      </el-form-item>

      <el-form-item label="适用车型">
        <el-input v-model="newPileForm.suitableVehicle"></el-input>
      </el-form-item>

      <el-form-item label="描述">
        <el-input v-model="newPileForm.pileDesc"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveNewPile">保存</el-button>
        <el-button @click="pileDialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 编辑充电桩 弹窗 -->
  <el-dialog v-model="pileEditDialogVisible" title="编辑充电桩">
    <el-form :model="editPileForm" label-width="120px">
      <el-form-item label="充电桩名称">
        <el-input v-model="editPileForm.pileName"></el-input>
      </el-form-item>

      <el-form-item label="充电桩编号">
        <!-- 编辑时通常不允许改编号 -->
        <el-input v-model="editPileForm.pileCode" disabled></el-input>
      </el-form-item>

      <el-form-item label="类型">
        <el-input v-model="editPileForm.pileType"></el-input>
      </el-form-item>

      <el-form-item label="功率(kW)">
        <el-input-number v-model="editPileForm.pilePower"></el-input-number>
      </el-form-item>

      <el-form-item label="型号">
        <el-input v-model="editPileForm.pileModel"></el-input>
      </el-form-item>

      <el-form-item label="适用车型">
        <el-input v-model="editPileForm.suitableVehicle"></el-input>
      </el-form-item>

      <el-form-item label="描述">
        <el-input v-model="editPileForm.pileDesc"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveEditPile">保存</el-button>
        <el-button @click="pileEditDialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'EditStationForm',
  props: {
    // 父组件传入要编辑的站点数据
    editData: {
      type: Object,
      required: true,
    },
  },
  emits: ['refresh', 'close'],
  setup(props, { emit }) {
    // 文件列表（图片上传用）
    const fileList = ref(
        props.editData.stationImgUrl
            ? [{ name: '站点图片', url: props.editData.stationImgUrl }]
            : []
    )

    // 图片上传回调
    const handleUploadSuccess = (response) => {
      if (response) {
        props.editData.stationImgUrl = response
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.error('图片上传失败')
      }
    }
    const handleUploadRemove = () => {
      fileList.value = []
      props.editData.stationImgUrl = ''
    }
    const handleExceed = () => {
      ElMessage.error('只能上传一张图片')
    }

    // 新增充电桩弹窗
    const pileDialogVisible = ref(false)
    // 编辑充电桩弹窗
    const pileEditDialogVisible = ref(false)

    // 新增表单
    const newPileForm = reactive({
      pileName: '',
      pileCode: '',
      pileType: '',
      pilePower: 0,
      pileModel: '',
      pileDesc: '',
      suitableVehicle: '',
    })

    // 编辑表单
    const editPileForm = reactive({
      pileName: '',
      pileCode: '',
      pileType: '',
      pilePower: 0,
      pileModel: '',
      pileDesc: '',
      suitableVehicle: '',
    })

    // 打开“新增充电桩”弹窗
    const openNewPileDialog = () => {
      Object.assign(newPileForm, {
        pileName: '',
        pileCode: '',
        pileType: '',
        pilePower: 0,
        pileModel: '',
        pileDesc: '',
        suitableVehicle: '',
      })
      pileDialogVisible.value = true
    }

    // 打开“编辑充电桩”弹窗
    const openEditPileDialog = (pile) => {
      Object.assign(editPileForm, pile)
      pileEditDialogVisible.value = true
    }

    // 新增 - 保存
    const saveNewPile = () => {
      // 如果 pileCode 已存在，可以根据需求做检查
      const index = props.editData.chargingPiles.findIndex(
          (p) => p.pileCode === newPileForm.pileCode
      )
      if (index !== -1) {
        ElMessage.error('该编号已存在，请更换')
        return
      }
      // 直接 push
      props.editData.chargingPiles.push({ ...newPileForm })
      // 关闭弹窗
      pileDialogVisible.value = false
    }

    // 编辑 - 保存
    const saveEditPile = () => {
      const index = props.editData.chargingPiles.findIndex(
          (p) => p.pileCode === editPileForm.pileCode
      )
      if (index !== -1) {
        // 更新原有项目
        props.editData.chargingPiles.splice(index, 1, { ...editPileForm })
      }
      // 关闭弹窗
      pileEditDialogVisible.value = false
    }

    // 删除桩
    const removePile = (index) => {
      ElMessageBox.confirm('确定要删除该充电桩吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            props.editData.chargingPiles.splice(index, 1)
            ElMessage.success('删除成功')
          })
          .catch(() => {
            ElMessage.info('取消删除')
          })
    }

    // 保存表单（站点信息 + 桩信息）
    const saveForm = async () => {
      // 转换开关值
      props.editData.enableEvaluation = props.editData.enableEvaluation ? 1 : 0
      props.editData.chargingPileCount = props.editData.chargingPiles.length

      try {
        await axios.post('/station/updateStationWithChargingPiles', {
          station: { ...props.editData },
          chargingPiles: [...props.editData.chargingPiles],
        })
        ElMessage.success('保存成功')
        emit('refresh') // 告诉父组件刷新列表
        emit('close') // 告诉父组件关闭弹窗
      } catch (error) {
        console.error('保存失败', error)
        ElMessage.error('保存失败')
      }
    }

    // 取消（站点编辑弹窗）
    const cancelDialog = () => {
      emit('close')
    }

    return {
      fileList,
      pileDialogVisible,
      pileEditDialogVisible,
      newPileForm,
      editPileForm,

      handleUploadSuccess,
      handleUploadRemove,
      handleExceed,

      openNewPileDialog,
      openEditPileDialog,
      saveNewPile,
      saveEditPile,
      removePile,
      saveForm,
      cancelDialog,
    }
  },
}
</script>

<style scoped>
.edit-station-form {
  padding-bottom: 20px;
}
</style>
